package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ApCollectionService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@Transactional
public class ApCollectionServiceImpl implements ApCollectionService {

    @Autowired
    private CacheService cacheService;

    /**
     * 文章收藏
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collectionBehavior(CollectionBehaviorDto dto) {
        // 1. 检查参数
        if(dto == null || checkParam(dto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 3. 文章收藏, 数据保存
        if(dto.getOperation() == 0){
            // 收藏

            // 判断是否已经收藏
            String collectionJson = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + dto.getEntryId(), user.getId().toString());
            if(StringUtils.isNotBlank(collectionJson)){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已收藏");
            }

            log.info("文章收藏，保存key:{},{},{}",BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(),dto.getEntryId().toString(), JSON.toJSONString(dto));
            cacheService.hPut(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(),dto.getEntryId().toString(), JSON.toJSONString(dto));
        }else{
            // 取消收藏
            log.info("文章收藏，删除key:{},{},{}",BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(),dto.getEntryId().toString());
            cacheService.hDelete(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(),dto.getEntryId().toString());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 检查 CollectionBehaviorDto 参数
     * @param dto
     * @return
     */
    private boolean checkParam(CollectionBehaviorDto dto) {
        if(dto.getEntryId() == null || dto.getPublishedTime() == null){
            return true;
        }
        if(dto.getOperation() > 1 || dto.getOperation() < 0){
            return true;
        }
        if(dto.getType() > 1 || dto.getType() < 0){
            return true;
        }
        return false;
    }
}
